package com.sobjal.android.utils;

import java.security.*;
import java.util.UUID;

/**
 * Allow to hash string in MD5
 * http://www.developpez.net/forums/d344729/java/general-java/apis/securite/appliquer-fonction-hachage-md5-texte/
 * 
 * @author Lionel Rywalski <lionel.rywalski@students.hevs.ch>
 * @author 9tita
 */
public class CryptUtils {
	/**
	 * function to hash
	 * 
	 * @param key
	 * @return
	 */
	public static String hash(String key) {
		
		byte[] uniqueKey = null;
		byte[] hash = null;
		StringBuffer hashString;
		uniqueKey = key.getBytes();
		
		try {
			hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
			
		} catch (NoSuchAlgorithmException e) {
			throw new Error("no MD5 support in this VM");
		}
		
		hashString = new StringBuffer();
			
		for (int i = 0; i < hash.length; ++i) {
			String hex = Integer.toHexString(hash[i]);
		
			if (hex.length() == 1) {
				hashString.append(0);
				hashString.append(hex.charAt(hex.length() - 1));
			} else {
				hashString.append(hex.substring(hex.length() - 2));
			}
		}
		return hashString.toString();
	}
	
	/**
	 * Generate a unique identifer
	 * http://www.javapractices.com/topic/TopicAction.do?Id=56
	 * 
	 * @return UUID the unique identifier
	 * 
	 */
	public static UUID GenerateUUID() {
		return UUID.randomUUID();
	}
}